package com.simpletour.qa.gateway.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * yml 网关跳过校验配置
 * @author zhaohw
 * @date 2018-06-27 11:17
 */
@Component
public class FilterSkipConfig {

    @Value("${gate.ignore.token.startWith}")
    private String startWithSkipToken;


    @Value("${gate.ignore.authority.startWith}")
    private String startWithSkipAuthority;

    /**
     * 是否为不校验JWT的路径(以开头匹配)
     * @param requestUri 当前请求uri
     * @param requestMethod 当前请求method
     * @return
     */
    public boolean isSkipTokenURIByStartWith(String requestUri,String requestMethod){
        return isSkipURIByStartWith(startWithSkipToken,requestUri,requestMethod);
    }

    /**
     * 是否为不校验API权限的路径(以开头匹配)
     * @param requestUri 当前请求uri
     * @param requestMethod 当前请求method
     * @return
     */
    public boolean isSkipAuthorityURIByStartWith(String requestUri,String requestMethod){
        return isSkipURIByStartWith(startWithSkipAuthority,requestUri,requestMethod);
    }

    /**
     * 以某地址开头的形式
     *      <p>yml配置形式: gate.ignore.*.startWith</p>
     * @param config yml中配置的跳过校验的路径
     * @param requestUri 当前请求uri
     * @param requestMethod 当前请求method
     * @return
     */
    private boolean isSkipURIByStartWith(String config , String requestUri,String requestMethod){
        for (String s : config.split(",")) {
            String[] configRequest = s.split("::");
            // uri后以::指定了请求方法
            if(configRequest.length == 2){
                if(requestUri.startsWith(configRequest[0].trim()) && requestMethod.equals(configRequest[1].trim())){
                    return true;
                }
            }
            // uri后未指定方法，即跳过所有类型请求
            else if(configRequest.length == 1){
                if(requestUri.startsWith(configRequest[0].trim())){
                    return true;
                }
            }
        }
        return false;
    }
}
